#! /usr/bin/env bash

# Copyright (c) 2024 XDream
# Copyright (c) 2024 bruceshu <shuhuan.bruce@gmail.com>
# 2024-9-20

set -e

FF_ARCH=$1

if [ -z "$FF_ARCH" ]; then
    echo "You must specific an architecture 'armv7a, arm64, all'.\n"
    exit 1
fi

PROJECT_DIR=`pwd`

SOURCE_DIR=$PROJECT_DIR/mydecoder

FF_ANDROID_PLATFORM=
FF_ANDROID_API=
FF_PLATFORM_CFG_FLAGS=
FF_CROSS_PREFIX=

FF_BUILD_NAME=
FF_CFG_FLAGS=
FF_EXTRA_CFLAGS=
FF_EXTRA_LDFLAGS=

echo ""
echo "--------------------"
echo "check env"
echo "--------------------"
. ./tools/do-detect-env.sh

echo ""
echo "--------------------"
echo "config env"
echo "--------------------"
if [ "$FF_ARCH" = "armv7a" ]; then
    FF_BUILD_NAME=mydecoder-armv7a
    FF_ANDROID_API=18
    FF_ANDROID_PLATFORM="android-18"
    FF_CROSS_PREFIX=armv7a-linux-androideabi
    FF_C_PREFIX=${FF_CROSS_PREFIX}${FF_ANDROID_API}
    FF_PLATFORM_CFG_FLAGS="armeabi-v7a"

elif [ "$FF_ARCH" = "arm64" ]; then
    FF_BUILD_NAME="mydecoder-arm64"
    FF_ANDROID_API=21
    FF_ANDROID_PLATFORM="android-21"
    FF_CROSS_PREFIX="aarch64-linux-android"
    FF_C_PREFIX=${FF_CROSS_PREFIX}${FF_ANDROID_API}
    FF_PLATFORM_CFG_FLAGS="arm64-v8a"

else
    echo "unknown architecture $FF_ARCH";
    exit 1
fi

echo ""
echo "--------------------"
echo "[*] export env"
echo "--------------------"
UNAME_S=$(echo $(uname -s) | tr '[A-Z]' '[a-z]')
FF_TOOLCHAIN_PATH=$ANDROID_NDK/toolchains/llvm/prebuilt/$UNAME_S-x86_64

export PATH=${FF_TOOLCHAIN_PATH}/bin:$PATH
export CC=${FF_C_PREFIX}-clang
export CXX=${FF_C_PREFIX}-clang++

FF_PREFIX=$PROJECT_DIR/output/android/$FF_BUILD_NAME

FF_CFG_FLAGS="$FF_CFG_FLAGS -DANDROID_NDK=$ANDROID_NDK"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK}/build/cmake/android.toolchain.cmake"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DANDROID_ABI=$FF_PLATFORM_CFG_FLAGS"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DANDROID_TOOLCHAIN=clang++"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DANDROID_STL=c++_shared"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DANDROID_PLATFORM=$FF_ANDROID_PLATFORM"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DCMAKE_SYSTEM_NAME=ANDROID"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DCMAKE_INSTALL_PREFIX=$FF_PREFIX"
FF_CFG_FLAGS="$FF_CFG_FLAGS -DCMAKE_BUILD_TYPE=Release"

echo ""
echo "--------------------"
echo "[*] compiling"
echo "--------------------"

if [ -d $SOURCE_DIR/build ]
then
    rm -rf $SOURCE_DIR/build
fi

mkdir -p ${SOURCE_DIR}/build
cd ${SOURCE_DIR}/build
echo "cmake .. $FF_CFG_FLAGS"
cmake .. $FF_CFG_FLAGS
make
make install
